package com.matrix.draft.sockettest.groupchatroom.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

public class ReadKeyEventHandler implements KeyEventHandler {
    @Override
    public void handle(SelectionKey key) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int len = channel.read(buffer);
            if (len <= 0) {
                throw new IOException();
            }
            System.out.println(new String(buffer.array(), 0, len, StandardCharsets.UTF_8));
            buffer.flip(); // 归位,方便其他对象再次读.
            // 通知其他客户端,其他所有客户端也应该收到广播
            SocketBufferBroadcaster.broadcast(
                    key.selector().keys().stream()
                            .filter(k -> k.channel() instanceof SocketChannel)
                            .map(k -> ((SocketChannel) k.channel()))
                            .collect(Collectors.toList()),
                    buffer,
                    channel
            );
        } catch (IOException e) {
            try {
                System.err.println("客户端"+channel.hashCode()+"异常,已销毁该连接");
                key.cancel();
                channel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

}
